//
//  OYActionSheet.m
//  qpyd
//
//  Created by 掌游网络 on 2017/7/20.
//  Copyright © 2017年 掌游网络. All rights reserved.
//

#import "OYActionSheet.h"

static const CGFloat kRowHeight = 50.0f;
static const CGFloat kRowLineHeight = 0.5f;
static const CGFloat kSeparatorHeight = 5.0f;
static const CGFloat kTitleFontSize = 13.0f;
static const CGFloat kButtonTitleFontSize = 15.0f;
static const NSTimeInterval kAnimateDuration = 0.25f;

@interface OYActionSheet ()

/** block回调 */
@property (nonatomic, copy) OYActionSheetBlock actionSheetBlock;
/** 背景图片 */
@property (nonatomic, strong) UIView *backgroundView;
/** 弹出视图 */
@property (nonatomic, strong) UIView *actionSheetView;

@end

@implementation OYActionSheet

- (void)dealloc {
#ifdef DEBUG
    NSLog(@"OYActionSheet dealloc");
#endif
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    
    return [self initWithTitle:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil handler:nil];
}

- (instancetype)initWithFrame:(CGRect)frame {
    
    return [self initWithTitle:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil handler:nil];
}

- (instancetype)initWithTitle:(NSString *)title
            cancelButtonTitle:(NSString *)cancelButtonTitle
       destructiveButtonTitle:(NSString *)destructiveButtonTitle
            otherButtonTitles:(NSArray *)otherButtonTitles
                      handler:(OYActionSheetBlock)actionSheetBlock {
    
    if (self = [super initWithFrame:CGRectZero]) {
        self.frame = [UIScreen mainScreen].bounds;
        _actionSheetBlock = actionSheetBlock;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        [self addGestureRecognizer:tap];
        
        CGFloat actionSheetHeight = 0;
        
        _backgroundView = [[UIView alloc] initWithFrame:self.bounds];
        _backgroundView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4f];
        _backgroundView.alpha = 0;
        [self addSubview:_backgroundView];
        
        _actionSheetView = [[UIView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height, self.bounds.size.width, actionSheetHeight)];
        _actionSheetView.backgroundColor = [UIColor colorWithRed:212.0f/255.0f green:214.0f/255.0f blue:216.0f/255.0f alpha:1.0f];
//        _actionSheetView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_actionSheetView];
        
        if (title.length > 0) {
            
            UIView *titleBgView = [[UIView alloc] init];
            titleBgView.backgroundColor = [UIColor whiteColor];
            [_actionSheetView addSubview:titleBgView];
            
            UILabel *titleLabel = [self GetAdaptiveLable:CGSizeMake(_actionSheetView.bounds.size.width - 60, 20) AndText:title font:kTitleFontSize];
            titleLabel.textColor = [UIColor colorWithRed:73.0f/255.0f green:80.0f/255.0f blue:90.0f/255.0f alpha:1.0f];
            [_actionSheetView addSubview:titleLabel];
            CGFloat titleW = titleLabel.bounds.size.width;
            CGFloat titleH = titleLabel.bounds.size.height + 40;
            
            titleLabel.frame = CGRectMake((_actionSheetView.bounds.size.width - titleW) / 2, actionSheetHeight, titleW, titleH);
            titleBgView.frame = CGRectMake(0, actionSheetHeight, _actionSheetView.bounds.size.width, titleH);
            
            actionSheetHeight += titleH;
        }
        
        UIImage *normalImage = [self imageWithColor:[UIColor colorWithRed:255.0f/255.0f green:255.0f/255.0f blue:255.0f/255.0f alpha:1.0f]];
        UIImage *highlightedImage = [self imageWithColor:[UIColor colorWithRed:249.0f/255.0f green:250.0f/255.0f blue:251.0f/255.0f alpha:1.0f]];
        
        if (destructiveButtonTitle.length > 0) {
            actionSheetHeight += kRowLineHeight;
            
            UIButton *destructiveButton = [UIButton buttonWithType:UIButtonTypeCustom];
            destructiveButton.frame = CGRectMake(0, actionSheetHeight, self.frame.size.width, kRowHeight);
            destructiveButton.autoresizingMask = UIViewAutoresizingFlexibleWidth;
            destructiveButton.tag = -1;
            destructiveButton.titleLabel.font = [UIFont systemFontOfSize:kButtonTitleFontSize];
            [destructiveButton setTitle:destructiveButtonTitle forState:UIControlStateNormal];
            [destructiveButton setTitleColor:[UIColor colorWithRed:227.0f/255.0f green:88.0f/255.0f blue:81.0f/255.0f alpha:1.0f] forState:UIControlStateNormal];
            [destructiveButton setBackgroundImage:normalImage forState:UIControlStateNormal];
            [destructiveButton setBackgroundImage:highlightedImage forState:UIControlStateHighlighted];
            [destructiveButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
            [_actionSheetView addSubview:destructiveButton];
            
            actionSheetHeight += kRowHeight;
        }
        
        if (otherButtonTitles.count > 0) {
            for (NSInteger i = 0; i < otherButtonTitles.count; i ++) {
                actionSheetHeight += kRowLineHeight;
                
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                button.frame = CGRectMake(0, actionSheetHeight, self.frame.size.width, kRowHeight);
                button.autoresizingMask = UIViewAutoresizingFlexibleWidth;
                button.tag = i + 1;
                button.titleLabel.font = [UIFont systemFontOfSize:kButtonTitleFontSize];
                [button setTitle:otherButtonTitles[i] forState:UIControlStateNormal];
                [button setTitleColor:[UIColor colorWithRed:33.0f/255.0f green:40.0f/255.0f blue:50.0f/255.0f alpha:1.0f] forState:UIControlStateNormal];
                [button setBackgroundImage:normalImage forState:UIControlStateNormal];
                [button setBackgroundImage:highlightedImage forState:UIControlStateHighlighted];
                [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
                [_actionSheetView addSubview:button];
                
                actionSheetHeight += kRowHeight;
            }
        }
        
        if (cancelButtonTitle.length > 0) {
        
            actionSheetHeight += kSeparatorHeight;
            
            UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
            cancelButton.frame = CGRectMake(0, actionSheetHeight, self.frame.size.width, kRowHeight);
            cancelButton.autoresizingMask = UIViewAutoresizingFlexibleWidth;
            cancelButton.tag = 0;
            cancelButton.titleLabel.font = [UIFont systemFontOfSize:kButtonTitleFontSize];
            [cancelButton setTitle:cancelButtonTitle forState:UIControlStateNormal];
            [cancelButton setTitleColor:[UIColor colorWithRed:33.0f/255.0f green:40.0f/255.0f blue:50.0f/255.0f alpha:1.0f] forState:UIControlStateNormal];
            [cancelButton setBackgroundImage:normalImage forState:UIControlStateNormal];
            [cancelButton setBackgroundImage:highlightedImage forState:UIControlStateHighlighted];
            [cancelButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
            [_actionSheetView addSubview:cancelButton];
            
            actionSheetHeight += kRowHeight;
            if ([[UIScreen mainScreen] bounds].size.width == 375.0f && [[UIScreen mainScreen] bounds].size.height == 812.0f) {
                actionSheetHeight += 34;
            }
        }
        
        _actionSheetView.frame = CGRectMake(0, self.frame.size.height, self.frame.size.width, actionSheetHeight);
    }
    return self;
}

#pragma mark - private method
- (UILabel *)GetAdaptiveLable:(CGSize)size AndText:(NSString *)contentStr font:(CGFloat)font {
    
    UILabel *contentLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    contentLbl.numberOfLines = 0;
    contentLbl.text = contentStr;
    contentLbl.font = [UIFont systemFontOfSize:font];
    
    NSMutableAttributedString *mAttrStr = [[NSMutableAttributedString alloc] initWithString:contentStr];
    NSMutableParagraphStyle *mParaStyle = [[NSMutableParagraphStyle alloc] init];
    [mParaStyle setLineSpacing:5.0];
    [mAttrStr addAttribute:NSParagraphStyleAttributeName value:mParaStyle range:NSMakeRange(0, [contentStr length])];
    [contentLbl setAttributedText:mAttrStr];
    contentLbl.textAlignment = NSTextAlignmentCenter;
    [contentLbl sizeToFit];
    
    return contentLbl;
}

- (UIImage *)imageWithColor:(UIColor *)color {

    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

- (void)dismiss {
    
    OYWeakSelf
    [UIView animateWithDuration:kAnimateDuration animations:^{
        OYStrongSelf
        self.backgroundView.alpha = 0.0f;
        self.actionSheetView.frame = CGRectMake(0, self.frame.size.height, self.frame.size.width, self.actionSheetView.frame.size.height);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)buttonClicked:(UIButton *)button {

    if (self.actionSheetBlock) {
        self.actionSheetBlock(button.tag);
    }
    
    [self dismiss];
}

- (void)tapClick:(UITapGestureRecognizer *)tap {
    if ([tap locationInView:self].y > self.frame.size.height - self.actionSheetView.frame.size.height) {
        return;
    }
    [self dismiss];
}

#pragma pubilc method
- (void)show {

//    // 在主线程中处理,否则在viewDidLoad方法中直接调用,会先加本视图,后加控制器的视图到UIWindow上,导致本视图无法显示出来,这样处理后便会优先加控制器的视图到UIWindow上
//    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//        
//        NSEnumerator *frontToBackWindows = [UIApplication.sharedApplication.windows reverseObjectEnumerator];
//        for (UIWindow *window in frontToBackWindows) {
//        
//            BOOL windowOnMainScreen = window.screen == UIScreen.mainScreen;
//            BOOL windowIsVisible = !window.hidden && window.alpha > 0;
//            BOOL windowLevelNormal = window.windowLevel == UIWindowLevelNormal;
//            
//            if(windowOnMainScreen && windowIsVisible && windowLevelNormal) {
//            
//                [window addSubview:self];
//                break;
//            }
//        }
//        
//        [UIView animateWithDuration:kAnimateDuration delay:0 usingSpringWithDamping:0.7f initialSpringVelocity:0.7f options:UIViewAnimationOptionCurveEaseInOut animations:^{
//            self.backgroundView.alpha = 1.0f;
//            self.actionSheetView.frame = CGRectMake(0, self.frame.size.height-self.actionSheetView.frame.size.height, self.frame.size.width, self.actionSheetView.frame.size.height);
//        } completion:nil];
//    }];
    
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    OYWeakSelf
    [UIView animateWithDuration:kAnimateDuration animations:^{
        OYStrongSelf
        self.backgroundView.alpha = 1.0f;
        self.actionSheetView.frame = CGRectMake(0, self.frame.size.height - self.actionSheetView.frame.size.height, self.frame.size.width, self.actionSheetView.frame.size.height);
    }];
}

@end
